package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.place;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.TreeResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryService;
import com.gzhryc.shared_device.common.CountryAreaUtils;
import com.gzhryc.shared_device.common.device.dao.models.PlaceDeviceCount;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStoreAddress;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStoreType;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreAddressService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreTypeService;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlacePhysicalStoreSearch;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.mng.dto.place.PlaceListItem;

/**
 * 实体店相关页面控制器
 * @version 2022-11-08
 */
public class PlacePhysicalStoreController {

    @Route(value = { "/place/physical_store/list.html" })
    public String list(HttpServletRequest request) {
        return "/place/physical_store/list.html";
    }

    @Route(value = "/place/physical_store/list.data")
    public ListResult<PlaceListItem> listData(HttpServletRequest request) {
        ListResult<PlaceListItem> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        PlacePhysicalStoreSearch search = WebUtils.getParameter(request, PlacePhysicalStoreSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            search.setUserId(loginUser.getId());

            result.getBody().setTotal(PlacePhysicalStoreService.self().countJoinBySearch(search));
            List<PlacePhysicalStore> placePhysicalStoreList = PlacePhysicalStoreService.self().findJoinBySearch(search, pageNo, pageLimit);
            if (placePhysicalStoreList != null && placePhysicalStoreList.size() > 0) {
                result.setCode(DtoConstants.SUCCESS, null);
                result.getBody().setData(new ArrayList<>());
                List<Long> placeIds = new ArrayList<>();
                String resDomain = WebConstants.getResDomain(request);
                for (PlacePhysicalStore physicalStore : placePhysicalStoreList) {
                    placeIds.add(physicalStore.getId());

                    PlaceListItem item = new PlaceListItem();
                    item.setId(physicalStore.getId());
                    if (StringTools.isNotBlank(physicalStore.getThumbnailImg())) {
                        item.setThumbnailImg(resDomain + physicalStore.getThumbnailImg());
                    }
                    item.setName(physicalStore.getName());
                    item.setTypeNames(physicalStore.getTypeNames());
                    item.setAreaName(physicalStore.getAreaName());
                    item.setState(physicalStore.getState());
                    item.setStateName(physicalStore.getStateName());
                    item.setCreateDate(physicalStore.getCreateDate());
                    result.getBody().getData().add(item);
                }

                List<PlaceDeviceCount> placeDeviceCountList = DeviceService.self().countPlaceByPlaceIds(placeIds);
                for (PlaceListItem item : result.getBody().getData()) {
                    if (placeDeviceCountList != null && placeDeviceCountList.size() > 0) {
                        for (PlaceDeviceCount placeDeviceCount : placeDeviceCountList) {
                            if (placeDeviceCount.getPlaceId().equals(item.getId())) {
                                item.setDeviceCount(placeDeviceCount.getDeviceCount().intValue());
                                break;
                            }
                        }
                    }
                }
            }
        }
        return result;
    }

    @Route(value = { "/place/physical_store/add.html" })
    public String add(HttpServletRequest request) {
        return "/place/physical_store/edit.html";
    }

    @Route(value = { "/place/physical_store/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败，请稍后再试");
        PlacePhysicalStore place = WebUtils.getParameter(request, PlacePhysicalStore.class);
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            if (StringTools.isBlank(place.getAreaCode())) {
                result.setMsg("请选择茶楼所在省市地区");
                return result;
            }
            String[] areaCodeStr = place.getAreaCode().split(",");
            String[] areaNames = CountryAreaUtils.getAreaNames(areaCodeStr);
            if (areaNames == null || areaNames.length < 3) {
                result.setMsg("请选择茶楼所在省市地区");
                return result;
            }

            if (StringTools.isNotBlank(areaNames[0])) {
                place.setProvince(areaNames[0]);
            }
            if (StringTools.isNotBlank(areaNames[1])) {
                place.setCity(areaNames[1]);
            }
            if (StringTools.isNotBlank(areaNames[2])) {
                place.setCityArea(areaNames[2]);
            }

            String[] typeCodes = place.getTypeCodes().split(",");
            String[] typeName = PlacePhysicalStoreTypeService.self().getNames(typeCodes);
            if (typeName != null && typeName.length > 0) {
                place.setTypeNames(StringUtils.join(typeName, ","));
            }
            place.setUserId(loginUser.getId());
            
            OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
            operateInfo.setOperator(EOperatorType.Agent.index(), loginUser.getFullName());
            operateInfo.setOperatorId(loginUser.getId());
            
            try {
                if (PlacePhysicalStoreService.self().add(place,operateInfo)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = { "/place/physical_store/info.html" })
    public String info(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            PlacePhysicalStore placePhysicalStore = PlacePhysicalStoreService.self().getById(id);
            if (placePhysicalStore != null && placePhysicalStore.getUserId().equals(loginUser.getId())) {
                WebUtils.setAttribute(request, placePhysicalStore);
                PlacePhysicalStoreAddress mailAddress = PlacePhysicalStoreAddressService.self().getById(id);
                if(mailAddress != null) {
                    request.setAttribute("mailAddress",mailAddress);
                }
            }
        }
        return "/place/physical_store/info.html";
    }

    @Route(value = { "/place/physical_store/update.html" })
    public String update(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            PlacePhysicalStore placePhysicalStore = PlacePhysicalStoreService.self().getById(id);
            if (placePhysicalStore != null && placePhysicalStore.getUserId().equals(loginUser.getId())) {
                WebUtils.setAttribute(request, placePhysicalStore);
            }
        }
        return "/place/physical_store/edit.html";
    }

    @Route(value = { "/place/physical_store/update.do" })
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败，请稍后再试");
        PlacePhysicalStore place = WebUtils.getParameter(request, PlacePhysicalStore.class);
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        PlacePhysicalStore temp = PlacePhysicalStoreService.self().getById(place.getId());
        if (temp != null && temp.getUserId().equals(loginUser.getId())) {
            try {
                if (StringTools.isBlank(place.getTypeCodes())) {
                    result.setMsg("请选择网点类型");
                    return result;
                }
                if (StringTools.isBlank(place.getAreaCode())) {
                    result.setMsg("请选择网点所在省市地区");
                    return result;
                }
                String[] areaCodeStr = place.getAreaCode().split(",");
                String[] areaNames = CountryAreaUtils.getAreaNames(areaCodeStr);
                if (areaNames == null || areaNames.length < 3) {
                    result.setMsg("请选择正确的省市地区");
                    return result;
                }

                if (StringTools.isNotBlank(areaNames[0])) {
                    place.setProvince(areaNames[0]);
                }
                if (StringTools.isNotBlank(areaNames[1])) {
                    place.setCity(areaNames[1]);
                }
                if (StringTools.isNotBlank(areaNames[2])) {
                    place.setCityArea(areaNames[2]);
                }

                String[] typeCodes = place.getTypeCodes().split(",");
                String[] typeName = PlacePhysicalStoreTypeService.self().getNames(typeCodes);
                if (typeName != null && typeName.length > 0) {
                    place.setTypeNames(StringUtils.join(typeName, ","));
                } else {
                    result.setMsg("请选择正确的网点类型");
                    return result;
                }

                if (PlacePhysicalStoreService.self().updateNotNull(place)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }else{
            result.setCode(DtoConstants.NOT_POWER,"无权限操作");
        }
        return result;
    }

    @Route(value = { "/place/physical_store/mail.html" })
    public String mail(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        PlacePhysicalStore placePhysicalStore = PlacePhysicalStoreService.self().getById(id);
        if(placePhysicalStore != null && placePhysicalStore.getUserId().equals(loginUser.getId())) {
            request.setAttribute("place",placePhysicalStore);
            PlacePhysicalStoreAddress mailAddress = PlacePhysicalStoreAddressService.self().getById(id);
            if(mailAddress != null) {
                WebUtils.setAttribute(request, mailAddress);
            }else{
                request.setAttribute("areaCode",placePhysicalStore.getAreaCode());
            }
        }
        return "/place/physical_store/mail.html";
    }

    @Route(value = { "/place/physical_store/mail/save.do" })
    public AjaxResult doSaveMail(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "保存失败，请稍后再试");
        PlacePhysicalStoreAddress mailAddress = WebUtils.getParameter(request, PlacePhysicalStoreAddress.class);
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        PlacePhysicalStore placePhysicalStore = PlacePhysicalStoreService.self().getById(mailAddress.getPlaceId());
        if(placePhysicalStore != null && placePhysicalStore.getUserId().equals(loginUser.getId())) {
            if (PlacePhysicalStoreAddressService.self().save(mailAddress)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        }else{
            result.setCode(DtoConstants.NOT_POWER,"无权限操作");
        }
        return result;
    }

    @Route(value = { "/place/physical_store/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败，请稍后再试");
        Long id = WebUtils.getLong(request, "id");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        PlacePhysicalStore temp = PlacePhysicalStoreService.self().getById(id);
        if (temp != null && temp.getUserId().equals(loginUser.getId())) {
            try {
                if (PlacePhysicalStoreService.self().deleteById(id)) {
                    //移除便携式电池部署
                    PortableEnergyBatteryService.self().undeployByPlaceId(id);
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }else{
            result.setCode(DtoConstants.NOT_POWER,"无权限操作");
        }
        return result;
    }

    @Route(value = "/place/gps/map.html")
    public String map(HttpServletRequest request) {
        return "/place/gps/map.html";
    }

    @Route(value = "/place/physical_store/type/select.data")
    public TreeResult<PlacePhysicalStoreType> selectData(HttpServletRequest request) {
        TreeResult<PlacePhysicalStoreType> result = new TreeResult<>(DtoConstants.SUCCESS);
        List<PlacePhysicalStoreType> typeTree = PlacePhysicalStoreTypeService.self().findTree();
        result.getBody().setData(typeTree);
        return result;
    }
}
